﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static editor.cfg.Config;

namespace editor.cfg
{
    /// <summary>
    /// ConfigControl.xaml 的交互逻辑
    /// </summary>
    public partial class ConfigControl : UserControl
    {

        private cfg.Config _config;

        private ObservableCollection<Record> _records;
        public ConfigControl()
        {
            this.DataContextChanged += this.OnDataContextChange;
            InitializeComponent();
        }

        private void OnDataContextChange(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                _config = (cfg.Config)e.NewValue;
                _records = _config.Records;
                //_records = new ObservableCollection<Record>(_config.Records);
                //Sort();
            }
        }


        private void Copy(object sender, RoutedEventArgs e)
        {
            if (recordheads.SelectedIndex >= 0)
            {
                //_records.Insert(recordheads.SelectedIndex + 1, CloneRecord(_records[recordheads.SelectedIndex]));
                _records.Add(CloneRecord(_records[recordheads.SelectedIndex]));
            }
        }

        private void Save(object sender, RoutedEventArgs e)
        {
            if (recordheads.SelectedIndex >= 0)
            {
                CheckSave(_config, _records[recordheads.SelectedIndex]);
            }
        }

        public static void CheckSave(Config config, Record r)
        {
            if (r.File == null)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = r.IndexFieldValue; // Default file name
                dlg.DefaultExt = ".xml"; // Default file extension
                dlg.Filter = "Xml Files (.xml)|*.xml"; // Filter files by extension

                bool? result = dlg.ShowDialog();
                if (result == true)
                {
                    var filePath = dlg.FileName;// System.IO.Path.Combine(config.DataDir, r.IndexFieldValue + ".xml");
                    if (!File.Exists(filePath))
                    {
                        r.File = filePath;
                        r.Save();
                    }
                    else
                    {
                        MessageBox.Show($"记录{r.IndexFieldValue},文件名{filePath}已存在,可能是记录id重复", "保存失败");
                    }
                }
            }
            else
            {
                r.Save();
            }
        }

        private void Remove(object sender, RoutedEventArgs e)
        {
            var index = recordheads.SelectedIndex;
            if (index >= 0)
            {
                var r = _records[index];
                if (r.File != null)
                {
                    var filePath = r.File;
                    if (File.Exists(filePath))
                    {
                        if (MessageBox.Show($"是否删除记录{r.IndexFieldValue},文件名{filePath}", "删除确认", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                        {
                            File.Delete(filePath);
                            _records.RemoveAt(index);
                        }
                    }
                    else
                    {
                        _records.RemoveAt(index);
                    }
                }
                else
                {
                    _records.RemoveAt(index);
                }

            }
        }

        private long CalcNextId()
        {
            return _records.Count == 0 ? 1 : _records.Select(r => long.TryParse(r.IndexFieldValue, out var v) ? v : 0).Max() + 1;
        }

        private Record New()
        {
            var r = new Record(null, _config.ValueType.NewDefault(), _config.Index) { IsDirty = true };
            r.IndexFieldValue = CalcNextId().ToString();
            return r;
        }

        private Record CloneRecord(Record old)
        {
            var r = new Record(null, old.Data.Clone(), _config.Index) { IsDirty = true };
            r.IndexFieldValue = CalcNextId().ToString();
            return r;
        }


        private void Append(object sender, RoutedEventArgs e)
        {
            _records.Add(New());
        }

        private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        {

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (!DynamicBeanControl.InScroll)
                {
                    ScrollViewer scrollviewer = sender as ScrollViewer;
                    scrollviewer.ScrollToVerticalOffset(scrollviewer.VerticalOffset - e.Delta);
                    e.Handled = true;
                }
                else
                {
                    DynamicBeanControl.InScroll = false;
                }
            });
        }

        private void Reset(object sender, RoutedEventArgs e)
        {
            _records[recordheads.SelectedIndex].Reset();
        }

        private void ShellOpen(object sender, RoutedEventArgs e)
        {
            var index = recordheads.SelectedIndex;
            if (index >= 0 && index < _records.Count)
            {
                var file = _records[index].File;
                if (!string.IsNullOrEmpty(file))
                {
                    ProcessStartInfo psi = new ProcessStartInfo(file);
                    psi.UseShellExecute = true;
                    Process.Start(psi);
                }
            }
        }

        private void ShellOpenDirectory(object sender, RoutedEventArgs e)
        {
            var index = recordheads.SelectedIndex;
            if (index >= 0 && index < _records.Count)
            {
                var file = _records[index].File;
                if (!string.IsNullOrEmpty(file))
                {
                    ProcessStartInfo psi = new ProcessStartInfo();
                    string args = string.Format("/e, /select, \"{0}\"", file);
                    psi.FileName = "explorer";
                    psi.Arguments = args;
                    //psi.UseShellExecute = true;
                    Process.Start(psi);
                }
            }
        }


        private void RenameFile(object sender, RoutedEventArgs e)
        {
            var index = recordheads.SelectedIndex;
            if (index >= 0 && index < _records.Count)
            {
                var r = _records[index];
                var oldFile = r.File;

                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.InitialDirectory = System.IO.Path.GetDirectoryName(oldFile);
                dlg.FileName = System.IO.Path.GetFileName(oldFile); // Default file name
                dlg.DefaultExt = ".xml"; // Default file extension
                dlg.Filter = "Xml Files (.xml)|*.xml"; // Filter files by extension

                bool? result = dlg.ShowDialog();
                if (result == true)
                {
                    var newFile = dlg.FileName;// System.IO.Path.Combine(config.DataDir, r.IndexFieldValue + ".xml");
                    if (!File.Exists(newFile))
                    {
                        File.Delete(oldFile);
                        r.File = newFile;
                        r.Save();
                    }
                    else
                    {
                        MessageBox.Show($"记录{r.IndexFieldValue},文件名{newFile}已存在,可能是记录id重复", "保存失败");
                    }
                }
            }
        }
    }
}
